package com.bu.web;

import java.net.URI;
import java.net.URISyntaxException;
import java.util.Collection;
import java.util.Comparator;
import java.util.Date;
import java.util.HashSet;
import java.util.Set;
import java.util.TreeSet;

import javax.jdo.PersistenceManager;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import javax.ws.rs.FormParam;
import javax.ws.rs.GET;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.QueryParam;
import javax.ws.rs.core.Context;
import javax.ws.rs.core.Response;

import org.springframework.beans.factory.config.BeanDefinition;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Component;

import com.bu.model.Problem;
import com.bu.model.Topic;
import com.bu.model.User;
import com.bu.service.PMF;
import com.sun.jersey.api.view.Viewable;

/**
 * @author xueqiang.mi
 * @since 2011-2-21
 */
@Path("/")
@Component
@Scope(BeanDefinition.SCOPE_PROTOTYPE)
public class DefaultResource extends BaseResource {
	private String topic;
	private String key;

	public Collection<Problem> getProblems() {
		Collection<Problem> problems;
		if (null != topic && !"".equals(topic)) { // search by topic
			problems = problemService.listByTopic(topic);
		} else { // search by key
			problems = problemService.list();
			Set<Problem> except = new HashSet<Problem>();
			if (null != key && !"".equals(key)) {
				for (Problem p : problems) {
					if (!p.getProblem().getValue().contains(key) && !p.getTopics().contains(key)) {
						except.add(p);
					}
				}
				problems.removeAll(except);
			}
		}
		if (null != problems && !problems.isEmpty()) {
			for (Problem p : problems) {
				String str = p.getProblem().getValue();
				str = str.replace("\\begin{itemize}", "<ul>").replace("\\end{itemize}", "</ul>");
				str = str.replace("\\begin{enumerate}", "<ol>").replace("\\end{enumerate}", "</ol>");
				str = str.replace("\\item", "<li>");
				p.setProblemHTML(str);
			}
		}
		return problems;
	}

	public Collection<Topic> getTopics() {
		Collection<Topic> topics = topicService.tree();
		for (Topic t : topics) {
			Set<String> children = new TreeSet<String>(new Comparator<String>() {
				@Override
				public int compare(String o1, String o2) {
					return o1.compareTo(o2);
				}
			});
			for (String subTopic : t.getChildren()) {
				children.add(subTopic);
			}
			t.setChildren(children);
		}
		return topics;
	}

	@POST
	@Path("register")
	public Response register(@FormParam("email") String email, @FormParam("password") String password,
			@FormParam("confirmPassword") String confirmPassword) throws URISyntaxException {
		if (null == email || "".equals(email) || !email.contains("@")) {
			return Response.ok(new Viewable("error", "Register Error: invalid email")).build();
		}
		if (!password.equals(confirmPassword)) {
			return Response.ok(new Viewable("error", "Register Error: invalid password")).build();
		}
		User user = new User();
		user.setEmail(email);
		user.setPassword(password);
		user.setCrtDate(new Date());
		PersistenceManager pm = PMF.get();
		try {
			pm.makePersistent(user);
		} finally {
			pm.close();
		}
		return Response.seeOther(new URI("/index")).build();
	}

	@POST
	@Path("login")
	public Response login(@FormParam("email") String email, @FormParam("password") String password, @Context HttpServletRequest request) {
		PersistenceManager pm = PMF.get();
		try {
			User user = pm.getObjectById(User.class, email);
			if (user != null && user.getPassword().equals(password)) {
				HttpSession session = request.getSession();
				session.setAttribute("email", email);
				return Response.seeOther(new URI("/index")).build();
			}
		} catch (Exception e) {
			e.printStackTrace();
			return Response.ok(new Viewable("error", "Login Error: user not found")).build();
		} finally {
			pm.close();
		}
		return Response.ok(new Viewable("error", "Login Error: invalid password")).build();
	}

	@GET
	@Path("logout")
	public Response logout(@Context HttpServletRequest request) throws URISyntaxException {
		HttpSession session = request.getSession();
		session.removeAttribute("email");
		return Response.seeOther(new URI("/index")).build();
	}

	@GET
	@Path("search")
	public Response search(@QueryParam("topic") String topic, @QueryParam("key") String key) {
		this.topic = topic;
		this.key = key;
		return Response.ok(new Viewable("index", this)).build();
	}
}
